import { forwardRef, useImperativeHandle, Ref, useEffect } from 'react';
import { Field } from '@formily/core';
import { useField } from '@formily/react';
import { Input } from 'antd';
import { useEvents } from '@inbiz/utils';
import { defaultProps } from '../../designer/schema';
import api from './api';
import './style.less';
type IProps = {
  value: string;
  // onChange: Function
  inbiz: { appInfo: { appId: string } };
  sourceModel: string;
  title: any;
  callBackEvents?: {
    onBeforeChange?: (v: string) => boolean;
  };
  emit?: () => void;
} & typeof defaultProps;

// const result=useModelList(undefined)

type IRef = Ref<ReturnType<typeof api>>;

const EformHidden = forwardRef((props: IProps, ref: IRef) => {
  const {
    callBackEvents,
    emit,
    defaultValueType,
    systemDefaultValue,
    inbiz,
    title,
    sourceModel,
    componentIsInline,
    ...others
  } = props;
  const isDesigner = inbiz.browser.designer;
  const field = useField<Field>();
  const [configEvents] = useEvents(props.callBackEvents, props.emit);
  useImperativeHandle(
    ref,
    () => ({
      ...api(configEvents, props),
    }),
    [],
  );

  useEffect(() => {
    if (!isDesigner && !componentIsInline) {
      field.hidden = true;
    }
  }, []);
  return isDesigner || componentIsInline ? (
    <Input {...others} value={props.value} className="EformHidden" disabled={true} />
  ) : null;
});
EformHidden.displayName = 'EformHidden';

(EformHidden as typeof EformHidden & IDefaultValueFormat<typeof defaultProps>).defaultValueFormat =
  (props: any): string | void => {
    if (props.defaultValueType == 'custom' && props.customValue) {
      return props.customValue;
    } else if (props.defaultValueType == 'system' && props.systemDefaultValue) {
      const { userInfoByToken } = props.inbiz.appInfo;
      const data = {
        System_Var_LoginUserID: userInfoByToken.ID,
        System_Var_LoginUserIdentityId: userInfoByToken.IdentityId,
        System_Var_LoginUserName: userInfoByToken.Name,
        System_Var_LoginUserDeptID: userInfoByToken.MainDepartmentId,
        System_Var_LoginUserDeptName: userInfoByToken.MainDepartmentName,
        System_Var_LoginUserPostID: userInfoByToken.MainPositionId,
        System_Var_LoginUserPostName: userInfoByToken.MainPositionName,
        System_Var_LoginUserAccount: userInfoByToken.Account,
      };
      let result = '';
      for (const key in data) {
        if (key == props.systemDefaultValue) {
          result = data[key];
        }
      }
      return result;
    }
  };

// export default connect(EformHidden);
export default EformHidden;
export type { IProps };
